package net.wanho.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.google.gson.Gson;

public class SMSUtil {
   // 阿里云访问密钥
   private String accessKeyId = "LTAI5tFfLgpD9LyUD6fUbhgh";
   private String accessKeySecret = "Rdh1QxkAejpYmM99oUbH0mgrVTnfoe";
   // 短信配置
   private String signName = "速通互联验证码";
   private String templateCode = "100001";

   /**
    * 发送短信验证码
    * @param phone 接收短信的手机号
    * @param code 验证码内容
    */
   public String sendMessage(String phone, String code) {
      try {
         Config config = new Config()
                 // 设置AccessKey ID
                 .setAccessKeyId(accessKeyId)
                 // 设置AccessKey Secret
                 .setAccessKeySecret(accessKeySecret);
         config.endpoint = "dypnsapi.aliyuncs.com"; // 设置访问域名

         // 实例化客户端
         Client client = new Client(config);

         // 创建请求对象
         SendSmsVerifyCodeRequest request = new SendSmsVerifyCodeRequest();

         // 设置请求参数
         request.setSignName(signName);
         request.setTemplateCode(templateCode);
         request.setPhoneNumber(phone);
         request.setReturnVerifyCode(true);
         // 模板参数需与短信模板中的变量对应，这里假设模板为"您的验证码是${code}，有效期${min}分钟"
         request.setTemplateParam("{\"code\":\"" + code + "\",\"min\":\"2\"}");

         // 获取响应
         SendSmsVerifyCodeResponse response = client.sendSmsVerifyCodeWithOptions(request, new RuntimeOptions());

         // 处理响应结果
         return response.getBody().getCode();

      } catch (TeaException e) {
         // 处理阿里云SDK异常
         System.err.println("短信服务异常: " + e.getMessage());
         e.printStackTrace();
      } catch (Exception e) {
         // 处理其他异常
         System.err.println("发送失败: " + e.getMessage());
         e.printStackTrace();
      }
      return "ERROR";
   }
}
